#include "TextureManager.h"
#include <SDL2/SDL_image.h>
#include <stdexcept>
#include <spdlog/spdlog.h>
#include "ResourceManager.h"

engine::resource::TextureManager::TextureManager(SDL_Renderer* renderer):m_renderer(renderer)
{
	if (!m_renderer)
	{
		throw std::runtime_error("TextureManager构造失败 -  渲染器指针为空");
	}
	spdlog::trace("TextureManager构造成功");
}

SDL_Texture* engine::resource::TextureManager::loadTexture(const std::string& filePath)
{
	auto it = m_textures.find(filePath);
	if (it != m_textures.end())
	{
		return it->second.get();
	}
	if (!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG))
	{
		spdlog::error("SDL_image init failed: {}", IMG_GetError());
		return nullptr;
	}
	SDL_Texture* raw_texture = IMG_LoadTexture(m_renderer, filePath.c_str());
	if (!raw_texture)
	{
		spdlog::error("加载纹理失败: {} - {}", filePath, SDL_GetError());
		return nullptr;
	}

	m_textures.emplace(filePath,std::unique_ptr<SDL_Texture, SDLTextureDeleter>(raw_texture));
	spdlog::info("加载纹理成功: {}", filePath);
	return raw_texture;
}

SDL_Texture* engine::resource::TextureManager::getTexture(const std::string& filePath)
{
	auto it = m_textures.find(filePath);
	if (it != m_textures.end())
	{
		return it->second.get();
	}
	spdlog::warn("获取纹理失败: {} - 纹理未加载", filePath);
	return loadTexture(filePath);
}

glm::vec2 engine::resource::TextureManager::getTextureSize(const std::string& filePath)
{
	SDL_Texture* texture = getTexture(filePath);
	if (!texture)
	{
		spdlog::warn("获取纹理尺寸失败: {} - 纹理未加载", filePath);
		return glm::vec2(0.0f, 0.0f);
	}
	int w = 0;
	int h = 0;
	if (SDL_QueryTexture(texture, nullptr, nullptr, &w, &h) == 0) 
	{
		return glm::vec2(static_cast<float>(w), static_cast<float>(h));
	}
	else
	{
		spdlog::error("获取纹理尺寸失败: {} - {}", filePath, SDL_GetError());
		return glm::vec2(0.0f, 0.0f);
	}
	return glm::vec2(0.0f, 0.0f);
}

void engine::resource::TextureManager::unloadTexture(const std::string& filePath)
{
	auto it = m_textures.find(filePath);
	if (it != m_textures.end())
	{
		m_textures.erase(it);
		spdlog::info("卸载纹理成功: {}", filePath);
	}
	else
	{
		spdlog::warn("卸载纹理失败: {} - 纹理未加载", filePath);
	}
}

void engine::resource::TextureManager::clearTexture()
{
	if (!m_textures.empty())
	{
		spdlog::info("清除所有纹理, 共计: {} 个", m_textures.size());
		m_textures.clear();
	}
}
